"""
Author: Jian SuiYue kaohx0214@yeah.net
Date: 2025-04-25 14:30:15
LastEditTime: 2025-05-15 17:08:11
FilePath: LibraryManagerStudio/web/routes/admin_api.py
"""

from fastapi import APIRouter, Depends, HTTPException, status, Query
from fastapi.responses import JSONResponse

from .token_api import generate_jwt
from ..deps import get_db
from ...database import DBManager
from ...datamodel import User

# 创建路由
router = APIRouter()


@router.post("/admin_login")
async def admin_login(
        id: str = Query(...),
        password: str = Query(...),
        db: DBManager = Depends(get_db)
):
    """
    Admin login.

    POST /admin_login?id={user_id}&password={password_encoding}
    Args:
        id: user id
        password: password_encoding
        db: DBManager
    """
    admin = db.get(User, filters={"id": id})
    if not admin.status or not admin.data:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"User ID {id} not found")
    if not admin.data[0]['is_admin']:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=f"You do not have administrator privileges.")
    if admin.data[0]['password'] != password:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=f"Invalid id or password.")

    token = generate_jwt(id)

    return JSONResponse(
        status_code=status.HTTP_200_OK,
        content={"status": True, "data": token, "message": "Login success"}
    )
